package com.fanyouzhao.ehome.web.servlet;

import com.fanyouzhao.ehome.entity.Cp;
import com.fanyouzhao.ehome.service.CpService;
import com.fanyouzhao.ehome.service.impl.CpServiceImpl;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet(name = "couponExportServlet", urlPatterns = "/couponExport")
public class couponExportServlet extends HttpServlet {

    private final CpService cpService = new CpServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fileName = "优惠券列表.xls";
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("优惠券列表");
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");

        String[] headers = {"序号", "ID", "名称", "详细描述", "使用规则", "领用有效期", "使用有效期", "是否上架"};
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<Cp> all = null;
        try {
            all = cpService.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //建sheet表，赋值表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 添加数据行:
        int rowNum = 1;
        for (Cp item : all) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(item.getId());
            dataRow.createCell(2).setCellValue(item.getName());
            dataRow.createCell(3).setCellValue(item.getDesc());
            dataRow.createCell(4).setCellValue(item.getRole());
            dataRow.createCell(5).setCellValue(dateFormat.format(item.getCollectExpire()));
            dataRow.createCell(6).setCellValue(dateFormat.format(item.getUseExpire()));
            dataRow.createCell(7).setCellValue(item.isInUse() ? "是" : "否");
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
